package com.dalei.vds;

import java.io.File;

import com.dalei.vds.environment.CurrentTask;
import com.dalei.vds.io.Dirctory;
import com.dalei.vds.util.RandomGUID;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ImageViewerActivity extends Activity {

	public static final String PARAMETER_GRID_ID = "gridId";

	public static final String PARAMETER_IMAGE_TITLE = "imageTitle";

	public static final String PARAMETER_IMAGE_VALUE = "imageValue";

	public static final int RESULT_MODIFIED = 0x00000003;

	public static final int RESULT_REMOVE = 0x00000004;

	private static final int REQUEST_CAMERA = 0x00000050;

	private static final String FIELD_IMAGESOURCE = "imageSoure";

	private static final String FIELD_IMAGESOURCE_PREVIOUS = "imageSourcePrivious";

	private static final String FIELD_MODIFIED = "modified";

	private int gridId;

	private int imageValue;

	private TextView title;

	private ImageView picture;

	private File imageSource;

	private File imageSourcePrivious;

	private boolean modified = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.imageviewer);

		title = (TextView) findViewById(R.id.imageviewer_title);
		picture = (ImageView) findViewById(R.id.imageviewer_picture);

		Intent intent = getIntent();
		gridId = intent.getIntExtra(PARAMETER_GRID_ID, -1);
		imageValue = intent.getIntExtra(PARAMETER_IMAGE_VALUE, -1);
		String imageTitle = intent.getStringExtra(PARAMETER_IMAGE_TITLE);

		title.setText(imageTitle);

		if ((gridId >= 0) && checkImageValue(imageValue)) {
			if (savedInstanceState == null) {
				imageSource = CurrentTask.getImages().get(imageValue);
				if (imageSource != null) {
					picture.setImageBitmap(thumbnails(imageSource));
				} else {
					AlertDialog.Builder builder = new AlertDialog.Builder(this);
					builder.setTitle(getString(R.string.prompt));
					builder.setMessage(getString(R.string.no_picture_prompt_msg));
					builder.setPositiveButton(getString(R.string.yes),
							new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									dialog.dismiss();

									File images = Dirctory.imagesDirctory();
									if (images != null) {
										imageSourcePrivious = imageSource;

										final String suffix = ".jpg";
										RandomGUID guid = new RandomGUID();
										String fileName = guid.toString();
										imageSource = new File(images, fileName
												+ suffix);

										Intent intent = new Intent(
												MediaStore.ACTION_IMAGE_CAPTURE);
										intent.putExtra(
												MediaStore.EXTRA_OUTPUT,
												Uri.fromFile(imageSource));
										startActivityForResult(intent,
												REQUEST_CAMERA);
									} else {
										Toast.makeText(
												getApplicationContext(),
												getApplicationContext()
														.getString(
																R.string.get_directory_failed),
												Toast.LENGTH_SHORT).show();
									}

								}

							});
					builder.setNegativeButton(getString(R.string.no),
							new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									dialog.dismiss();

									Intent intent = new Intent();
									intent.putExtras(getIntent());
									setResult(RESULT_CANCELED, intent);
									finish();
								}

							});
					builder.create().show();
				}
			} else {
				File source = (File) savedInstanceState
						.getSerializable(FIELD_IMAGESOURCE);
				File sourcePrivious = (File) savedInstanceState
						.getSerializable(FIELD_IMAGESOURCE_PREVIOUS);

				if (source != null) {
					if (source.exists()) {
						picture.setImageBitmap(thumbnails(source));
					} else {
						if (sourcePrivious != null && sourcePrivious.exists()) {
							picture.setImageBitmap(thumbnails(sourcePrivious));
						} else {
							AlertDialog.Builder builder = new AlertDialog.Builder(
									this);
							builder.setTitle(getString(R.string.prompt));
							builder.setMessage(getString(R.string.no_picture_prompt_msg));
							builder.setPositiveButton(getString(R.string.yes),
									new DialogInterface.OnClickListener() {

										public void onClick(
												DialogInterface dialog,
												int which) {
											// TODO Auto-generated method stub
											dialog.dismiss();

											File images = Dirctory
													.imagesDirctory();
											if (images != null) {
												imageSourcePrivious = imageSource;

												final String suffix = ".jpg";
												RandomGUID guid = new RandomGUID();
												String fileName = guid
														.toString();
												imageSource = new File(images,
														fileName + suffix);

												Intent intent = new Intent(
														MediaStore.ACTION_IMAGE_CAPTURE);
												intent.putExtra(
														MediaStore.EXTRA_OUTPUT,
														Uri.fromFile(imageSource));
												startActivityForResult(intent,
														REQUEST_CAMERA);
											} else {
												Toast.makeText(
														getApplicationContext(),
														getApplicationContext()
																.getString(
																		R.string.get_directory_failed),
														Toast.LENGTH_SHORT)
														.show();
											}

										}

									});
							builder.setNegativeButton(getString(R.string.no),
									new DialogInterface.OnClickListener() {

										public void onClick(
												DialogInterface dialog,
												int which) {
											// TODO Auto-generated method stub
											dialog.dismiss();

											Intent intent = new Intent();
											intent.putExtras(getIntent());
											setResult(RESULT_CANCELED, intent);
											finish();
										}

									});
							builder.create().show();
						}
					}
				} else {
					AlertDialog.Builder builder = new AlertDialog.Builder(this);
					builder.setTitle(getString(R.string.prompt));
					builder.setMessage(getString(R.string.no_picture_prompt_msg));
					builder.setPositiveButton(getString(R.string.yes),
							new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									dialog.dismiss();

									File images = Dirctory.imagesDirctory();
									if (images != null) {
										imageSourcePrivious = imageSource;

										final String suffix = ".jpg";
										RandomGUID guid = new RandomGUID();
										String fileName = guid.toString();
										imageSource = new File(images, fileName
												+ suffix);

										Intent intent = new Intent(
												MediaStore.ACTION_IMAGE_CAPTURE);
										intent.putExtra(
												MediaStore.EXTRA_OUTPUT,
												Uri.fromFile(imageSource));
										startActivityForResult(intent,
												REQUEST_CAMERA);
									} else {
										Toast.makeText(
												getApplicationContext(),
												getApplicationContext()
														.getString(
																R.string.get_directory_failed),
												Toast.LENGTH_SHORT).show();
									}

								}

							});
					builder.setNegativeButton(getString(R.string.no),
							new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									dialog.dismiss();

									Intent intent = new Intent();
									intent.putExtras(getIntent());
									setResult(RESULT_CANCELED, intent);
									finish();
								}

							});
					builder.create().show();
				}
			}
		} else {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(getString(R.string.warning));
			builder.setMessage(getString(R.string.invalid_parameter));
			builder.setPositiveButton(getString(R.string.ok),
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.dismiss();

							Intent intent = new Intent();
							intent.putExtras(getIntent());
							setResult(RESULT_CANCELED, intent);
							finish();
						}
					});
			builder.create().show();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.imageviewer_options_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		Intent intent = null;
		switch (item.getItemId()) {
		case R.id.imageviewer_menuitem_retake:
			File images = Dirctory.imagesDirctory();
			if (images != null) {
				imageSourcePrivious = imageSource;

				final String suffix = ".jpg";
				RandomGUID guid = new RandomGUID();
				String fileName = guid.toString();
				imageSource = new File(images, fileName + suffix);

				intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_OUTPUT,
						Uri.fromFile(imageSource));
				startActivityForResult(intent, REQUEST_CAMERA);
			} else {
				Toast.makeText(
						getApplicationContext(),
						getApplicationContext().getString(
								R.string.get_directory_failed),
						Toast.LENGTH_SHORT).show();
			}
			break;
			
		case R.id.imageviewer_menuitem_remove:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(getString(R.string.prompt));
			builder.setMessage(getString(R.string.remove_picture_prompt_msg));
			builder.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					CurrentTask.getImages().remove(imageValue);
					
					Intent intent = new Intent();
					intent.putExtras(getIntent());
					setResult(RESULT_REMOVE, intent);
					finish();
				}
			});
			builder.setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					dialog.dismiss();
				}
			});
			builder.create().show();
			break;
			
		case R.id.imageviewer_menuitem_exit:
			intent = new Intent();
			intent.putExtras(getIntent());
			setResult(RESULT_CANCELED, intent);
			finish();
			break;
			
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);

		outState.putSerializable(FIELD_IMAGESOURCE, imageSource);
		outState.putSerializable(FIELD_IMAGESOURCE_PREVIOUS,
				imageSourcePrivious);
		outState.putBoolean(FIELD_MODIFIED, modified);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onRestoreInstanceState(savedInstanceState);

		imageSource = (File) savedInstanceState
				.getSerializable(FIELD_IMAGESOURCE);
		imageSourcePrivious = (File) savedInstanceState
				.getSerializable(FIELD_IMAGESOURCE_PREVIOUS);
		modified = savedInstanceState.getBoolean(FIELD_MODIFIED);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case REQUEST_CAMERA:
			switch (resultCode) {
			case RESULT_OK:
				picture.setImageBitmap(thumbnails(imageSource));
				CurrentTask.getImages().put(imageValue, imageSource);
				modified = true;
				break;

			case RESULT_CANCELED:
				imageSource = imageSourcePrivious;
				break;

			default:
				break;
			}
			break;

		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			Intent intent = new Intent();
			intent.putExtras(getIntent());
			if (modified) {
				setResult(RESULT_MODIFIED, intent);
			} else {
				setResult(RESULT_CANCELED, intent);
			}
			finish();
			break;

		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

	private boolean checkImageValue(int value) {
		final int[] in = new int[] { 5, 6, 7, 8, 9, 10, 11, 12 };
		for (int i = 0; i < in.length; i++) {
			if (value == in[i]) {
				return true;
			}
		}
		return false;
	}

	private Bitmap thumbnails(File file) {
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inSampleSize = 5;
		return BitmapFactory.decodeFile(file.getAbsolutePath(), opts);
	}
}
